from django import http
from django.contrib.auth.backends import ModelBackend

from users.models import User

class UsernameMobileLogin(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """

        :param request:
        :param username:
        :param password:
        :param kwargs:
        :return:  返回User对象
        """

        try:
            user=User.objects.get(username=username)
        except Exception as e:
            pass
            # return http.HttpResponseForbidden('用户名不存在')
        if not user:
            try:
                user=User.objects.get(mobile=username)
            except Exception as e:
                return None
        #密码没有检查通过
        if not user.check_password(password):
            return None

        return user